package com.fluagen.example.vertx.templates;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.templ.HandlebarsTemplateEngine;

public class MainVerticle extends AbstractVerticle {

	public static final String HOST = "127.0.0.1";
	public static final int PORT = 8083;

	public static Logger log = LoggerFactory.getLogger(MainVerticle.class);

	@Override
	public void start(Future<Void> future) throws Exception {
		Router router = Router.router(vertx);
		router.route("/*").handler(BodyHandler.create());
		final HandlebarsTemplateEngine engine = HandlebarsTemplateEngine.create();

		router.get("/").handler(this::login);
		router.post("/create/oplogin").handler(ctx -> {
			
			HttpServerRequest request = ctx.request();
			
			String clientKey = request.getParam("client_id");
			String clientSecret = request.getParam("client_secret");
			String userType = request.getParam("user_type");
			String cbURL = request.getParam("redirect_uri");
			String vf = request.getParam("view_format");
			String tenantId = request.getParam("tenant_id");

			String openLoginURL = request.getParam("open_login_uri");

			Map<String, String> signParams = new HashMap<String, String>();
			signParams.put("client_id", clientKey);
			signParams.put("tenant_id", tenantId);
			signParams.put("redirect_uri", cbURL);

			String sign = MD5Util.md5(signParams, clientSecret);
			StringBuilder redirectURL = new StringBuilder(openLoginURL);

			try {
				redirectURL.append("?");
				redirectURL.append("client_id").append("=").append(clientKey);
				redirectURL.append("&");
				redirectURL.append("tenant_id").append("=").append(tenantId);
				redirectURL.append("&");
				redirectURL.append("redirect_uri").append("=").append(URLEncoder.encode(cbURL, "UTF-8"));
				redirectURL.append("&");
				redirectURL.append("user_type").append("=").append(userType);
				redirectURL.append("&");
				redirectURL.append("view_format").append("=").append(vf);
				redirectURL.append("&");
				redirectURL.append("sign").append("=").append(sign);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			ctx.put("openLoginURL", redirectURL.toString());
			log.info("openLoginURL:"+redirectURL.toString());
			
			engine.render(ctx, "templates", "/oplogin", res ->{
				if (res.succeeded()) {
					ctx.response().end(res.result());
				} else {
					ctx.fail(res.cause());
				}
			});
		});

		JsonObject config = context.config();

		vertx.createHttpServer().requestHandler(router::accept).listen(config.getInteger("http.port", PORT),
				config.getString("http.address", HOST), result -> {
					if (result.succeeded()) {
						future.complete();
						log.info("Open API Client APP start");

					} else {
						future.fail(result.cause());
					}

				});
	}

	private void login(RoutingContext context) {
		HttpServerResponse response = context.response();
		response.sendFile("public/index.html");
	}

	private void loginOpenAPI(RoutingContext context) {


		HttpServerRequest request = context.request();

		String clientKey = request.getParam("client_id");
		String clientSecret = request.getParam("client_secret");
		String userType = request.getParam("user_type");
		String cbURL = request.getParam("redirect_uri");
		String vf = request.getParam("view_format");
		String tenantId = request.getParam("tenant_id");

		String openLoginURL = request.getParam("open_login_uri");

		Map<String, String> signParams = new HashMap<String, String>();
		signParams.put("client_id", clientKey);
		signParams.put("tenant_id", tenantId);
		signParams.put("redirect_uri", cbURL);

		String sign = MD5Util.md5(signParams, clientSecret);
		StringBuilder redirectURL = new StringBuilder(openLoginURL);

		try {
			redirectURL.append("?");
			redirectURL.append("client_id").append("=").append(clientKey);
			redirectURL.append("tenant_id").append("=").append(tenantId);
			redirectURL.append("redirect_uri").append("=").append(URLEncoder.encode(cbURL, "UTF-8"));
			redirectURL.append("user_type").append("=").append(userType);
			redirectURL.append("view_format").append("=").append(vf);
			redirectURL.append("sign").append("=").append(sign);
			HttpServerResponse response = context.response();
			response.setStatusCode(200).end(redirectURL.toString());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		context.put("openLoginURL", redirectURL.toString());

	}

	public static void main(String[] args) {

		Runner.deploy(MainVerticle.class);
	}
}
